//
//  search_Detail_iPhone_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 28-03-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "search_Detail_iPhone_ViewController.h"
#import "classGenericCell.h"
#import "CustomCell.h"
#import "dao.h"
#import "UITabBarController+hidable.h"
#import "MyCollectionViewCellSearch.h"
#import "Product_Detail_ViewController.h"
#import "AppRecord.h"
#import "IconDownloader.h"

@interface search_Detail_iPhone_ViewController ()

@property (nonatomic, strong) NSMutableDictionary *imageDownloadsInProgress;

@end

@implementation search_Detail_iPhone_ViewController{
    
    CGFloat startContentOffset;
    CGFloat lastContentOffset;
    BOOL hidden;
}

@synthesize tableViewSearch;
@synthesize dataArraySearch = _dataArraySearch;
@synthesize CollectionViewSearch;
@synthesize imgGridOrder;
@synthesize viewApplyFilter;
@synthesize btnClearFilter;
@synthesize viewLoading, objActivyLoading;
@synthesize json;

@synthesize imageObjectsBusqueda = _imageObjectsBusqueda;

#pragma mark - The Magic!

bool blnExistFilter = NO;
NSTimer *timerLoadingSearch;

- (void)hideTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds);
                         tabBar.frame = tabFrame;
                         content.frame = window.bounds;
                     }];
    
    UIView *parent2 = viewApplyFilter.superview; // UILayoutContainerView
    UIView *content2 = [parent2.subviews objectAtIndex:0];  // UITransitionView
    UIView *window2 = parent2.superview;

    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame2 = viewApplyFilter.frame;
                         tabFrame2.origin.y = CGRectGetMaxY(window2.bounds);
                         viewApplyFilter.frame = tabFrame2;
                         content2.frame = window2.bounds;
                     }];
}

- (void)showTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
}

-(void)expand
{
    if(hidden)
        return;
    
    hidden = YES;
    
    [self.tabBarController setTabBarHidden:YES
                                  animated:YES];
    
/*
    UIView *parent2 = viewApplyFilter.superview; // UILayoutContainerView
    UIView *content2 = [parent2.subviews objectAtIndex:0];  // UITransitionView
    UIView *window2 = parent2.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame2 = viewApplyFilter.frame;
                         tabFrame2.origin.y = CGRectGetMaxY(window2.bounds);
                         viewApplyFilter.frame = tabFrame2;
                         content2.frame = window2.bounds;
                     }];
*/

/*
    viewApplyFilter.frame = CGRectMake(0,0,0, 0);
    viewApplyFilter.hidden = YES;
    
    tableViewSearch.frame = CGRectMake(0,0,320, 464);
    CollectionViewSearch.frame = CGRectMake(0,0,320, 464);
*/
    //0,0,320,464
    
    //  [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)contract
{
    if(!hidden)
        return;
    
    hidden = NO;
    
    [self.tabBarController setTabBarHidden:NO
                                  animated:YES];
/*
    viewApplyFilter.frame = CGRectMake(0,0,320, 40);
    viewApplyFilter.hidden = NO;

    tableViewSearch.frame = CGRectMake(0,40,320, 464);
    CollectionViewSearch.frame = CGRectMake(0,40,320, 464);
*/
//0,40,320,464
    
//  [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    startContentOffset = lastContentOffset = scrollView.contentOffset.y;
    //NSLog(@"scrollViewWillBeginDragging: %f", scrollView.contentOffset.y);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    CGFloat currentOffset = scrollView.contentOffset.y;
    CGFloat differenceFromStart = startContentOffset - currentOffset;
    CGFloat differenceFromLast = lastContentOffset - currentOffset;
    lastContentOffset = currentOffset;
    
    if((differenceFromStart) < 0)
    {
        // scroll up
        if(scrollView.isTracking && (abs(differenceFromLast)>1))
            [self expand];
    }
    else {
        if(scrollView.isTracking && (abs(differenceFromLast)>1))
            [self contract];
    }

}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView
{
    [self contract];
    return YES;
}

//-----------------------------------------------------------------------------------------
//Observación: Grilla cuadriculada

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArraySearch.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCellSearch *myCell = [collectionView
                                          dequeueReusableCellWithReuseIdentifier:@"MyCell"
                                          forIndexPath:indexPath];
    
//  myCell.imgImageView.image = [UIImage imageNamed:@"img_llave.png"];
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    myCell.lblTrademark.text = objCell.strTrademark;
    
    myCell.lblTitleLabel.text = objCell.strTitleLabel;
    
    myCell.lblPrice.text = objCell.strPrice;
    
    myCell.lbldiscount.text = objCell.strDiscount;
//-------------------------------------------------------
    myCell.imgImageViewOfferPercent.hidden = NO;
    myCell.lbldiscount.hidden = NO;
    myCell.lblQty.text = objCell.strQty;
    
    if ([objCell.strDiscount  isEqual: @"0"]) {
        myCell.imgImageViewOfferPercent.hidden = YES;
        myCell.lbldiscount.hidden = YES;
    }
    
//--------------------------------------------------------------------------------------------------
    AppRecord *appRecord = [self.imageObjectsBusqueda objectAtIndex:indexPath.row];
//--------------------------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //1.- Imagen normal
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
//---------------------------------------------------------------------------------------------------
    
    if (image == nil) {
        
        [self startIconDownloadCollection:appRecord forIndexPath:indexPath celda:myCell];
    }else{
        
        CGSize itemSize = CGSizeMake(87, 76);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
        CGRect imageRect = CGRectMake(5, 3, itemSize.width, itemSize.height);
        [image drawInRect:imageRect];
        myCell.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        myCell.imgImageView.frame = CGRectMake(5, 3, 87, 76);
        
        [self startIconDownloadCollection:appRecord forIndexPath:indexPath celda:myCell ];
    }
    
    return myCell;
}

-(void)setBackProductoDetail{
    
    dao *objDAO = [[dao alloc] init];
    
    if ([objDAO obtainProductBack] == -1) { //No hay nada
        [objDAO deleteProductBack];
        [objDAO insertProductBack:1];   //Indica que busca desde el Home
        
    }else if ([objDAO obtainProductBack] == 2){
        [objDAO deleteProductBack];
        [objDAO insertProductBack:2];   //Indica que busca desde el Home
        
    }
    else{
        [objDAO deleteProductBack];
        [objDAO insertProductBack:1];   //Indica que busca desde el Home
        
    }
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    NSString *strTitleLabel = @"";
    
    strTitleLabel = objCell.strTitleLabel;

//Indicamos el producto actual seleccionado para luego obtener su información
    dao *objDAO = [[dao alloc] init];

    NSLog(@"objCell.strIdProducto = %@", objCell.strIdProducto);
    
    [objDAO deleteCurrentProduct];
    [objDAO insertCurrentProduct:[objCell.strIdProducto intValue]];
    [objDAO insertCurrentGridOrder:1]; //1: Lista 2: Grilla
    
    //Almacenamos el registro en una tabla y enviamos a la página siguiente.
    NSLog(@"strTitleLabel = %@", strTitleLabel);
    
    //Definimos como son las funciones de retorno Back de los siguientes formularios
    [self setBackProductoDetail];
    
    //------------------------------------------------
     UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
     Product_Detail_ViewController *profileViewController = (Product_Detail_ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"ProductoDetail"];
     
     [profileViewController.navigationController setNavigationBarHidden:NO];
     profileViewController.hidesBottomBarWhenPushed = YES;
     
     [self.navigationController pushViewController:profileViewController animated:YES];
    //------------------------------------------------
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    NSString *strTitleLabel = @"";
    
    strTitleLabel = objCell.strTitleLabel;
    
    //Indicamos el producto actual seleccionado para luego obtener su información
    dao *objDAO = [[dao alloc] init];
    
    [objDAO deleteCurrentProduct];
    [objDAO insertCurrentProduct:[objCell.strIdProducto intValue]];
    [objDAO insertCurrentGridOrder:2]; //1: Lista 2: Grilla
    
    //Almacenamos el registro en una tabla y enviamos a la página siguiente.
    NSLog(@"strTitleLabel = %@", strTitleLabel);

    //Definimos como son las funciones de retorno Back de los siguientes formularios
    [self setBackProductoDetail];
    
    //------------------------------------------------
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    Product_Detail_ViewController *profileViewController = (Product_Detail_ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"ProductoDetail"];
    
    [profileViewController.navigationController setNavigationBarHidden:NO];
    profileViewController.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:profileViewController animated:YES];
    
}
//-----------------------------------------------------------------------------------------

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [_dataArraySearch count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }

    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    cell.lblTrademark.text = objCell.strTrademark;
    cell.lblTitleLabel.text = objCell.strTitleLabel;

//Ordenamos en la grilla
    cell.lblPrice.text = objCell.strPrice;
    cell.lblPriceDuplicated.text = objCell.strPrice;
    
    cell.lbldiscount.text = objCell.strDiscount;
    cell.lblOfferPrice.text = objCell.strOfferPrice;
    
    cell.imgImageViewOfferPercent.hidden = NO;
    cell.lbldiscount.hidden = NO;
    cell.lblQty.text = objCell.strQty;
    
    if ([objCell.strDiscount  isEqual: @"0"]) {

    //Ocultamos el precio oferta
        cell.lblOfferPrice.hidden = YES;
        cell.viewLineOfferPrice.hidden = YES;

    //Desplegamos el precio normal
        cell.lblPriceDuplicated.hidden = NO;
        cell.lblPrice.hidden = YES;
        
    }else{
        //Ocultamos el precio oferta
        cell.lblOfferPrice.hidden = NO;
        cell.viewLineOfferPrice.hidden = NO;
        
        //Desplegamos el precio normal
        cell.lblPriceDuplicated.hidden = YES;
        cell.lblPrice.hidden = NO;
    }
    
    if ([objCell.strDiscount  isEqual: @"0"]) {
        cell.imgImageViewOfferPercent.hidden = YES;
        cell.lbldiscount.hidden = YES;
    }

    AppRecord *appRecord = [self.imageObjectsBusqueda objectAtIndex:indexPath.row];
    
    //-----------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //1.- Imagen normal
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    //-----------------------------------------------------------------------------------
    
    if (image == nil) {
        
        [self startIconDownload:appRecord forIndexPath:indexPath celda:cell];
    }else{
/*
        CGSize itemSize = CGSizeMake(70, 52);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
        CGRect imageRect = CGRectMake(0, 12, itemSize.width, itemSize.height);
        [image drawInRect:imageRect];
        cell.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.imgImageView.frame = CGRectMake(0, 12, 70, 52);
*/
        CGSize itemSize = CGSizeMake(87, 76);
        UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
        CGRect imageRect = CGRectMake(3, 3, itemSize.width, itemSize.height);
        [image drawInRect:imageRect];
        cell.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.imgImageView.frame = CGRectMake(3, 3, 87, 76);
        
        [self startIconDownload:appRecord forIndexPath:indexPath celda:cell ];
    }
    
//  cell.imgImageView.image = [UIImage imageNamed:@"img_llave.png"];
    
    return cell;
}

- (void)startIconDownloadCollection:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath celda:(MyCollectionViewCellSearch *) celda
{
    IconDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:indexPath];
    
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = appRecord;
        [iconDownloader setCompletionHandler:^{
  
            CGSize itemSize = CGSizeMake(87, 76);
            UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
            CGRect imageRect = CGRectMake(5, 3, itemSize.width, itemSize.height);
            [appRecord.appIcon drawInRect:imageRect];
            celda.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

//--------------------------------------------------------------------------------------------------------------------
//          celda.imgImageView.image = appRecord.appIcon;
            celda.imgImageView.frame = CGRectMake(5, 3, 87, 76);
            
            [self.imageDownloadsInProgress removeObjectForKey:indexPath];
            
//--------------------------------------------------------------------------------------------------------------------
            classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
            
            NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
            NSData* data = UIImageJPEGRepresentation(appRecord.appIcon, 1);
            [data writeToFile:path atomically:YES];
//--------------------------------------------------------------------------------------------------------------------
            
        }];
        [self.imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
    }
}

- (void)startIconDownload:(AppRecord *)appRecord forIndexPath:(NSIndexPath *)indexPath celda:(CustomCell *) celda
{
    IconDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:indexPath];
    
    if (iconDownloader == nil)
    {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.appRecord = appRecord;
        [iconDownloader setCompletionHandler:^{
            
            //***
            CGSize itemSize = CGSizeMake(87, 76);
            UIGraphicsBeginImageContextWithOptions(itemSize, NO, 0.0f);
            CGRect imageRect = CGRectMake(3, 3, itemSize.width, itemSize.height);
            [appRecord.appIcon drawInRect:imageRect];
            celda.imgImageView.image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            //***
            
//          celda.imgImageView.image = appRecord.appIcon;
            celda.imgImageView.frame = CGRectMake(3, 3, 87, 76);
            
            [self.imageDownloadsInProgress removeObjectForKey:indexPath];
            
            //-----------------------------------------------------------------------------------------------------------------
            classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                 NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSString *strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", objCell.strIdProducto];
            
            NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
            NSData* data = UIImageJPEGRepresentation(appRecord.appIcon, 1);
            [data writeToFile:path atomically:YES];
            //-----------------------------------------------------------------------------------------------------------------
            
        }];
        [self.imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
    }
}

-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

- (void) retrieveGenericSearch:(NSString *) strTipoGrilla{
    
    if ([strTipoGrilla  isEqual: @"Lista"]) {

        self.tableViewSearch.hidden = NO;
       [self.tableViewSearch reloadData];
        
    }else{ //Grilla

        self.tableViewSearch.hidden = YES;
       [self.CollectionViewSearch reloadData];
    }
    
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

- (void) retrieveDataSearch{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];
    
    _imageObjectsBusqueda = [[NSMutableArray alloc] init];
    
    self.tableViewSearch.hidden = NO;

    dao *objDAO = [[dao alloc] init];

    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }

    //Limpiamos la base de datos local
    [objDAO deleteProducts:intIdUsuario];

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
//1.-Búsqueda generica
    NSString *strStringSearch = [prefs stringForKey:@"StringSearch"];
    
//1.-Búsqueda por departamento
    NSString *strIdDepartment = [prefs stringForKey:@"strIdDepartment"];

    NSString * params;
    //------------------------------------------------------------------------------

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonBusquedaProducto.aspx"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];

    if (![strIdDepartment  isEqual: @"0"]) {

        params =[NSString stringWithFormat:@"strJsonBase=JsonBusquedaProductoPorDepartamento&strBusqueda=&stridDepartamentoProducto=%@",  strIdDepartment];
        
    }else{

        params =[NSString stringWithFormat:@"strJsonBase=JsonBusquedaProducto&strBusqueda=%@",  strStringSearch];
    }
    
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];//NSNonLossyASCIIStringEncoding  NSUTF8StringEncoding
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                               NSLog(@"Data = %@",text);
//*****************************************************
                                                               NSLog(@"Load búsqueda perfecto!!!");
                                                               
                                                               int intMinPrice = 0;
                                                               int intMaxPrice = 0;
                                                               
                                                               NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                               newStr = [self stringByRemovingControlCharacters:newStr];
                                                               
                                                               NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
                                                               
                                                               json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
                                                               
                                                               //[{"idp":"5", "dp":"Alicate corte 6 1/4” 84009. ", "dcom":"Alicate corte 6 1/4” diagonal 84009 rojo/amarillo. ", "over":"", "sku":"120873 ", "nr":"0", "nv":"0", "pn":"1900", "po":"300", "dcto":"70", "tof":"29", "idm":"4", "dmp":"stanley", "img":"5/126_4.jpg"}]
                                                               
                                                               for (int i = 0; i<json.count; i++)
                                                               {
                                                                   NSString *strTitleLabel = [[json objectAtIndex:i] objectForKey:@"dp"];
                                                                   NSString *strSubtitleLabel = @"";
                                                                   NSString *strTrademark = [[json objectAtIndex:i] objectForKey:@"dmp"];
                                                                   NSString *strIdmark = [[json objectAtIndex:i] objectForKey:@"idm"];
                                                                   
                                                                   NSString *strSKU = [[json objectAtIndex:i] objectForKey:@"sku"];
                                                                   NSString *strIdProducto = [[json objectAtIndex:i] objectForKey:@"idp"];
                                                                   NSString *strReviews = [[json objectAtIndex:i] objectForKey:@"nr"];
                                                                   NSString *strPrice = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"po"] doubleValue]]; //@"$39.990 C/U"
                                                                   NSString *strOfferPrice = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"pn"] doubleValue]];
                                                                   NSString *strPriceDuplicated = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"po"] doubleValue]];  //@"$39.990 C/U"
                                                                   
                                                                   NSString *strDiscount = [[json objectAtIndex:i] objectForKey:@"dcto"];
                                                                   NSString *strPorcentaje = @"";
                                                                   
                                                                   if (![strDiscount  isEqual: @"0"]) { //Si viene una oferta se destaca
                                                                       
                                                                       strOfferPrice = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"pn"] doubleValue]];
                                                                       strPorcentaje = @"%";
                                                                       strDiscount = [NSString stringWithFormat:@"-%@%@", strDiscount, strPorcentaje];
                                                                   }
                                                                   
                                                                   NSString *strOfferTime = @"";
                                                                   NSString *strQty = [[json objectAtIndex:i] objectForKey:@"unidad"];
                                                                   
                                                                   AppRecord *appRecord = [[AppRecord alloc] init];
                                                                   
                                                                   classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
                                                                   
                                                                   appRecord.imageURLString = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/ImagenProductos/%@", [[json objectAtIndex:i] objectForKey:@"img"]];
                                                                   
                                                                   [_imageObjectsBusqueda addObject:appRecord];
                                                                   
                                                                   //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                   //Quitamos los caracteres especiales para grabar en SqlLite
                                                                   NSString * replace = [strPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                                                                   replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                                                                   int intPrecio = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                                                                   
                                                                   replace = [strOfferPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                                                                   replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                                                                   int intPrecioOferta = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                                                                   
                                                                   NSLog(@"intPrecioOferta =%i", intPrecioOferta);
                                                                   
                                                                   NSLog(@"strIdProducto =%i", [strIdProducto intValue]);
                                                                   
                                                                   //Para no hacer otra llamada, calculamos el menor y mayor valor de la lista obtenida
                                                                   if (i == 0) {
                                                                       intMinPrice = intPrecio;
                                                                       intMaxPrice = intPrecio;
                                                                   }else{
                                                                       
                                                                       if (intPrecioOferta > intMaxPrice) {
                                                                           intMaxPrice = intPrecio;
                                                                       }
                                                                       
                                                                       if (intPrecioOferta < intMinPrice) {
                                                                           intMinPrice = intPrecio;
                                                                       }
                                                                   }
                                                                   
                                                                   //[objDAO insertProduct:intIdUsuario intIdProducto:[strIdProducto intValue] strDescProd:strTitleLabel strDescComplementaria:strSubtitleLabel strOverview:@"" strSKU:strSKU intNroReviews:[strReviews intValue] intNroValoraciones:0 intPrecio:intPrecio intPrecioOferta:intPrecioOferta intDescuento:[strDiscount intValue] strTiempoOferta:strOfferTime intIdMarca:[strIdmark intValue] strDescripcionMarca:strTrademark];
                                                                   //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                   
                                                                   [_dataArraySearch addObject:objCell];
                                                               }
                                                               
                                                               [self.tableViewSearch reloadData];
                                                               
                                                               NSLog(@"intMinPrice =%i", intMinPrice);
                                                               NSLog(@"intMaxPrice =%i", intMaxPrice);
                                                               
                                                               //-----------------------------------------------------------------
                                                               //Almacenamos los valores desde y hasta de los filtros de precios
                                                               
                                                               if ([objDAO obtainExistUserFilterPrice:intIdUsuario] > 0 ) {
                                                                   
                                                                   //-----------------------------------------------------------------
                                                                   //Almacenamos los valores desde y hasta de los filtros de precios
                                                                   NSArray *arrayFilterPrice = [objDAO obtainUserFilterPrice:intIdUsuario];
                                                                   
                                                                   NSLog(@"arrayFilterPrice[0]: %@", arrayFilterPrice[0]);
                                                                   NSLog(@"arrayFilterPrice[1]: %@", arrayFilterPrice[1]);
                                                                   NSLog(@"arrayFilterPrice[2]: %@", arrayFilterPrice[2]);
                                                                   
                                                                   //Si el filtro existe, no toco los datos
                                                                   //[objDAO deleteUserFilterPrice:intIdUsuario];
                                                                   //[objDAO insertUserFilterPrice:intIdUsuario intPriceDesde:intMinPrice intPriceHasta:intMaxPrice intPriceCurrent:intMinPrice];
                                                                   
                                                               }else{
                                                                   [objDAO deleteUserFilterPrice:intIdUsuario];
                                                                   [objDAO insertUserFilterPrice:intIdUsuario intPriceDesde:intMinPrice intPriceHasta:intMaxPrice intPriceCurrent:intMinPrice];
                                                               }
                                                               //-----------------------------------------------------------------
                                                               
                                                               viewLoading.hidden = YES;
                                                               
//**************************************************
                                                           }else{
                                                               viewLoading.hidden = YES;
                                                           }
                                                       }];
    [dataTask resume];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//  [self.tabBarController setTabBarHidden:hidden animated:NO];

}

- (IBAction)removeFilter:(id)sender{

    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = 0;
    intIdUsuario = [objDAO obtainCurrentIdUser];

    [objDAO deleteUserFilterPrice:intIdUsuario];
//  [objDAO insertUserFilterPrice:intIdUsuario intPriceDesde:20990 intPriceHasta:60990 intPriceCurrent:20990];
    
    [objDAO deleteUserFilterMarc:intIdUsuario];
    [objDAO deleteUserTipoOrdenamiento:intIdUsuario];

    btnClearFilter.hidden = YES;

    //-----------------------------------------
    //Nueva funcionalidad.
    viewLoading.hidden = NO;
    
//  timerLoadingSearch = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loadingProducts:) userInfo:nil repeats:YES];
    
    timerLoadingSearch = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loadingInitCloud:) userInfo:nil repeats:YES];
    
    //-----------------------------------------
}

-(void) crearUsrCloud{
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraUsuario.aspx?strJsonBase=JsonUsuarioIns"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Crear Usuario perfecto");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"usr":"21"}]
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             int intIdUsuario = [  [[json objectAtIndex:0] objectForKey:@"usr"] intValue];
             
             NSLog(@"intIdUsuario =%i", intIdUsuario);
             
             dao *objDAO = [[dao alloc] init];
             
             [objDAO deleteCurrentIdUser];
             [objDAO insertCurrentIdUser:intIdUsuario];
             
             //strSocialLoginId = 3 //Correo
             [objDAO deleteUserSistem:intIdUsuario];
             
             int intRetorno = [objDAO insertUserSistem:intIdUsuario strUser:@"" strPassword:@"" strSocialLoginId:@"3" strEmail:@""];
             
             NSLog(@"intRetorno =%i", intRetorno);
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iphone_header.png"] forBarMetrics:UIBarMetricsDefault];
    
    [self.tabBarController setTabBarHidden:NO animated:YES];
    
//------------------------------------------------------------------------------------------------------
//Observación: Si volvemos al home marcamos que se recargue por perderse el flujo del Storyboard padre.
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:@"LoadHomeFirst" forKey:@"keyToLookupString"];
//------------------------------------------------------------------------------------------------------
    
    [tableViewSearch setAllowsSelection:YES];
    
    int intIdUsuario = 0;

    dao *objDAO = [[dao alloc] init];
    
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {

        [self crearUsrCloud];
    }

//1.- Filtro de precio
    if ( [objDAO obtainExistUserFilterPrice:intIdUsuario] > 0 )  {

        NSArray *arrayFilterPrice = [objDAO obtainUserFilterPrice:intIdUsuario];
        
        NSLog(@"arrayFilterPrice[0]: %@", arrayFilterPrice[0]);
        NSLog(@"arrayFilterPrice[2]: %@", arrayFilterPrice[2]);
        
        double dblPriceFrom = [arrayFilterPrice[0] doubleValue];
        double dblPriceCurrent = [arrayFilterPrice[2] doubleValue];
        
        if (dblPriceFrom != dblPriceCurrent) {
             blnExistFilter = YES;
        }
    }

//2.- Filtro de marca
    if ( [objDAO obtainUserFilterMarc:intIdUsuario] > 0 )  {
        
        blnExistFilter = YES;
    }

//3.- Filtro de ordenamiento
    if ( [objDAO obtainUserTipoOrdenamiento:intIdUsuario] > 0 )  {
        
        blnExistFilter = YES;
    }

//4.- Si hay filtro, aparecemos el botón
    if (blnExistFilter == YES) {
        btnClearFilter.hidden = NO;
    }
    
//Significa que viene del retorno del producto, por lo que la grilla debe cargar rapidamente y no volver a ir al Cloud
    if ([objDAO obtainCurrentProduct] > 0) {
        [objDAO deleteCurrentProduct];

        int intTipoOrdenamientoGrillas = [objDAO obtainCurrentGridOrder];

        //-1 = No existe registro en la tabla
        if ((intTipoOrdenamientoGrillas == 1) || (intTipoOrdenamientoGrillas == -1)) {

            [self retrieveGenericSearch:@"Lista"];
            
        }else{
            [self retrieveGenericSearch:@"Grilla"];
        }

        [objDAO deleteCurrentGridOrder];
        
    }else{
    //-----------------------------------------
    //Nueva funcionalidad.
        viewLoading.hidden = NO;
        
      timerLoadingSearch = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loadingInitCloud:) userInfo:nil repeats:YES];
        
    //-----------------------------------------
    }
    
    [self loadTabbar];
}

- (void) loadTabbar{
    //-------------------------------------------------------------------------------------
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    NSArray *ArrayResumeShoppingCart;
    NSString *strTotalCarro = @"0";
    
    
    ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUsuario];
    
    if (ArrayResumeShoppingCart.count > 0) {
        
        NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
        NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
        
        strTotalCarro = ArrayResumeShoppingCart[1];
    }
    
    //----------------------------------
    UITabBar *tabBar = self.tabBarController.tabBar; //tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
    UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
    UITabBarItem *tabBarItem5 = [tabBar.items objectAtIndex:4];
    
    tabBarItem1.selectedImage = [[UIImage imageNamed:@"icon_inicio_activo.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.image = [[UIImage imageNamed:@"icon_inicio.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem1.title = @"Inicio";
    
    tabBarItem2.selectedImage = [[UIImage imageNamed:@"icon_buscar_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.image = [[UIImage imageNamed:@"icon_buscar.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem2.title = @"Buscar";
    
    tabBarItem3.selectedImage = [[UIImage imageNamed:@"icon_carro_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.image = [[UIImage imageNamed:@"icon_carro.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem3.title = @"Carro";
    tabBarItem3.badgeValue = strTotalCarro;
    
    tabBarItem4.selectedImage = [[UIImage imageNamed:@"icon_cuenta_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.image = [[UIImage imageNamed:@"icon_cuenta.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem4.title = @"Cuenta";
    
    tabBarItem5.selectedImage = [[UIImage imageNamed:@"icon_chat_activo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.image = [[UIImage imageNamed:@"icon_chat.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
    tabBarItem5.title = @"Chat";
    //----------------------------------
}

- (void) retrieveDataSearchFilter{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];
    
    _imageObjectsBusqueda = [[NSMutableArray alloc] init];
    
    self.tableViewSearch.hidden = NO;
    
    dao *objDAO = [[dao alloc] init];
    
    int intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    //1.-Búsqueda generica
    NSString *strStringSearch = [prefs stringForKey:@"StringSearch"];
    
    NSString * params;
    
    //------------------------------------------------------------------------------
    //Buscamos los filtros para aplicarlos
    //strNAZ           =   -1
    //strNZA           =   -1
    //strMAP           =   -1
    //strMEP           =    1
    //strMAR           =   -1
    //strMPO           =   -1

    NSString *strIdMarca, *strNAZ, *strNZA, *strMAP, *strMEP, *strMAR, *strMPO, *strPrecioDesde, *strPrecioHasta, *strPrecioSeleccionado;
    int intIdTipoOrdenamiento = -1;

    strPrecioDesde = @"-1";
    strPrecioHasta = @"-1";
    
    //1.- Filtro de precio
    if ( [objDAO obtainExistUserFilterPrice:intIdUsuario] > 0 )  {
        
        NSArray *arrayFilterPrice = [objDAO obtainUserFilterPrice:intIdUsuario];
        strPrecioDesde = arrayFilterPrice[0];
        strPrecioHasta = arrayFilterPrice[1];
        strPrecioSeleccionado = arrayFilterPrice[2];

        //Este es el precio del slider en la ventana siguiente
        strPrecioDesde = strPrecioSeleccionado;
    }
    
    //2.- Filtro de marca
    strIdMarca =  [NSString stringWithFormat:@"%i", [objDAO obtainUserFilterMarc:intIdUsuario]]; //-1 sin datos, cumple con lo requerido en el Sql remoto
 
    intIdTipoOrdenamiento = [objDAO obtainUserTipoOrdenamiento:intIdUsuario];

    strNAZ = @"-1";
    strNZA = @"-1";
    strMAP = @"-1";
    strMEP = @"-1";
    strMAR = @"-1";
    strMPO = @"-1";
    
    if (intIdTipoOrdenamiento > 0) {
        
        switch (intIdTipoOrdenamiento)
        {
            case 1:
                strNAZ = @"1";
                break;
            case 2:
                strNZA = @"1";
                break;
            case 3:
                strMAP = @"1";
                break;
                
            case 4:
                strMEP = @"1";
                break;
            case 5:
                strMAR = @"1";
                break;
            case 6:
                strMPO = @"1";
                break;
//          default:
//              NSLog (@"Integer out of range");
//              break;
        }
    }else{

      //Si no hay ordenamiento, ordeno por precio asc por defecto
        strMEP = @"1";
    }
    
    //------------------------------------------------------------------------------
    //&strIdMarca=19&strNAZ=-1&strNZA=-1&strMAP=-1&strMEP=1&strMAR=-1&strMPO=-1&strPrecioDesde=-1&strPrecioHasta=-1

    //&strIdMarca=%@&strNAZ=%@&strNZA=%@&strMAP=%@&strMEP=%@&strMAR=%@&strMPO=%@&strPrecioDesde=%@&strPrecioHasta=%@
    
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonBusquedaProducto.aspx"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];

    params =[NSString stringWithFormat:@"strJsonBase=JsonBusquedaProductoFiltroOrden&strBusqueda=%@&strIdMarca=%@&strNAZ=%@&strNZA=%@&strMAP=%@&strMEP=%@&strMAR=%@&strMPO=%@&strPrecioDesde=%@&strPrecioHasta=%@",  strStringSearch,strIdMarca, strNAZ,strNZA, strMAP, strMEP, strMAR, strMPO, strPrecioDesde, strPrecioHasta];
    
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];//NSNonLossyASCIIStringEncoding  NSUTF8StringEncoding
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                               NSLog(@"Data = %@",text);
                                                               //**************
                                                               NSLog(@"Load búsqueda perfecto!!!");
                                                               
                                                               int intMinPrice = 0;
                                                               int intMaxPrice = 0;
                                                               
                                                               NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                               newStr = [self stringByRemovingControlCharacters:newStr];
                                                               
                                                               NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
                                                               
                                                               json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
                                                               
                                                               //[{"idp":"5", "dp":"Alicate corte 6 1/4” 84009. ", "dcom":"Alicate corte 6 1/4” diagonal 84009 rojo/amarillo. ", "over":"", "sku":"120873 ", "nr":"0", "nv":"0", "pn":"1900", "po":"300", "dcto":"70", "tof":"29", "idm":"4", "dmp":"stanley", "img":"5/126_4.jpg"}]
                                                               
                                                               for (int i = 0; i<json.count; i++)
                                                               {
                                                                   NSString *strTitleLabel = [[json objectAtIndex:i] objectForKey:@"dp"];
                                                                   NSString *strSubtitleLabel = @"";
                                                                   NSString *strTrademark = [[json objectAtIndex:i] objectForKey:@"dmp"];
                                                                   NSString *strIdmark = [[json objectAtIndex:i] objectForKey:@"idm"];
                                                                   
                                                                   NSString *strSKU = [[json objectAtIndex:i] objectForKey:@"sku"];
                                                                   NSString *strIdProducto = [[json objectAtIndex:i] objectForKey:@"idp"];
                                                                   NSString *strReviews = [[json objectAtIndex:i] objectForKey:@"nr"];
                                                                   NSString *strPrice = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"po"] doubleValue]]; //@"$39.990 C/U"
                                                                   NSString *strOfferPrice = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"pn"] doubleValue]];
                                                                   NSString *strPriceDuplicated = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"po"] doubleValue]];  //@"$39.990 C/U"
                                                                   
                                                                   NSString *strDiscount = [[json objectAtIndex:i] objectForKey:@"dcto"];
                                                                   NSString *strPorcentaje = @"";
                                                                   
                                                                   if (![strDiscount  isEqual: @"0"]) { //Si viene una oferta se destaca
                                                                       
                                                                       strOfferPrice = [self formatCurrencyValue:[[[json objectAtIndex:i] objectForKey:@"pn"] doubleValue]];
                                                                       strPorcentaje = @"%";
                                                                       strDiscount = [NSString stringWithFormat:@"-%@%@", strDiscount, strPorcentaje];
                                                                   }
                                                                   
                                                                   NSString *strOfferTime = @"";
                                                                   NSString *strQty = [[json objectAtIndex:i] objectForKey:@"unidad"];
                                                                   
                                                                   AppRecord *appRecord = [[AppRecord alloc] init];
                                                                   
                                                                   classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strSubtitleLabel andTrademark:strTrademark andIdMark:strIdmark andSKU:strSKU andStrIdProducto:strIdProducto andReviews:strReviews andstrPrice:strPrice andOfferPrice:strOfferPrice andstrPriceDuplicated:strPriceDuplicated andDiscount:strDiscount andOfferTime:strOfferTime andQty:strQty];
                                                                   
                                                                   appRecord.imageURLString = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/ImagenProductos/%@", [[json objectAtIndex:i] objectForKey:@"img"]];
                                                                   
                                                                   [_imageObjectsBusqueda addObject:appRecord];
                                                                   
                                                                   //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                   //Quitamos los caracteres especiales para grabar en SqlLite
                                                                   NSString * replace = [strPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                                                                   replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                                                                   int intPrecio = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                                                                   
                                                                   replace = [strOfferPrice stringByReplacingOccurrencesOfString: @ "$" withString: @ ""];
                                                                   replace = [replace stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
                                                                   int intPrecioOferta = [ [replace stringByReplacingOccurrencesOfString: @ " C/U" withString: @ ""] intValue];
                                                                   
                                                                   NSLog(@"intPrecioOferta =%i", intPrecioOferta);
                                                                   
                                                                   NSLog(@"strIdProducto =%i", [strIdProducto intValue]);
                                                                   
                                                                   //Para no hacer otra llamada, calculamos el menor y mayor valor de la lista obtenida
                                                                   if (i == 0) {
                                                                       intMinPrice = intPrecio;
                                                                       intMaxPrice = intPrecio;
                                                                   }else{
                                                                       
                                                                       if (intPrecioOferta > intMaxPrice) {
                                                                           intMaxPrice = intPrecio;
                                                                       }
                                                                       
                                                                       if (intPrecioOferta < intMinPrice) {
                                                                           intMinPrice = intPrecio;
                                                                       }
                                                                   }
                                                                   //-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
                                                                   
                                                                   [_dataArraySearch addObject:objCell];
                                                               }
                                                               
                                                               [self.tableViewSearch reloadData];
                                                               
                                                               NSLog(@"intMinPrice =%i", intMinPrice);
                                                               NSLog(@"intMaxPrice =%i", intMaxPrice);
                                                               
                                                               //-----------------------------------------------------------------
                                                               //Almacenamos los valores desde y hasta de los filtros de precios
                                                               
                                                               if ([objDAO obtainExistUserFilterPrice:intIdUsuario] > 0 ) {
                                                                   
                                                                   //-----------------------------------------------------------------
                                                                   //Almacenamos los valores desde y hasta de los filtros de precios
                                                                   NSArray *arrayFilterPrice = [objDAO obtainUserFilterPrice:intIdUsuario];
                                                                   
                                                                   NSLog(@"arrayFilterPrice[0]: %@", arrayFilterPrice[0]);
                                                                   NSLog(@"arrayFilterPrice[1]: %@", arrayFilterPrice[1]);
                                                                   NSLog(@"arrayFilterPrice[2]: %@", arrayFilterPrice[2]);
                                                                   
                                                                   //Si el filtro existe no toco los datos
                                                                   //[objDAO deleteUserFilterPrice:intIdUsuario];
                                                                   //[objDAO insertUserFilterPrice:intIdUsuario intPriceDesde:intMinPrice intPriceHasta:intMaxPrice intPriceCurrent:intMinPrice];
                                                                   
                                                               }else{
                                                                   [objDAO deleteUserFilterPrice:intIdUsuario];
                                                                   [objDAO insertUserFilterPrice:intIdUsuario intPriceDesde:intMinPrice intPriceHasta:intMaxPrice intPriceCurrent:intMinPrice];
                                                               }
                                                               //-----------------------------------------------------------------
                                                               
                                                               viewLoading.hidden = YES;
                                                               
                                                               //**************
                                                           }else{
                                                               viewLoading.hidden = YES;
                                                           }
                                                       }];
    [dataTask resume];
    
}

- (void) loadingInitCloud:(NSTimer *) timer {
    
    //Detenemos el timer
    [timerLoadingSearch invalidate];
    timerLoadingSearch = nil;
    
    /*
     1.- Lanzar un NSURL Session Task hacia el cloud sincrónico
     2.- Con respuesta grabar en sqlLite
     3.- Mandar mensaje de alerta
     */

    if (blnExistFilter) {

        [self retrieveDataSearchFilter];
        
    }else{

        [self retrieveDataSearch];
    }
    
    //Si todo lo anterior sucede bien ocultar la vista
//  viewLoading.hidden = YES;
}

- (void) loadingProducts:(NSTimer *) timer {
    
    //Detenemos el timer
    [timerLoadingSearch invalidate];
    timerLoadingSearch = nil;
    
    /*
     1.- Lanzar un NSURL Session Task hacia el cloud sincrónico
     2.- Con respuesta grabar en sqlLite
     3.- Mandar mensaje de alerta
     */

//  [self retrieveDataSearch];
    [self retrieveGenericSearch:@"Lista"];
    
    //Si todo lo anterior sucede bien ocultar la vista
    viewLoading.hidden = YES;
    
}

- (void) loadingProductsGrid:(NSTimer *) timer {
    
    //Detenemos el timer
    [timerLoadingSearch invalidate];
    timerLoadingSearch = nil;
    
    /*
     1.- Lanzar un NSURL Session Task hacia el cloud sincrónico
     2.- Con respuesta grabar en sqlLite
     3.- Mandar mensaje de alerta
     */
    
//  [self retrieveDataCollectionView];
    [self retrieveGenericSearch:@"Grilla"];
    
    //Si todo lo anterior sucede bien ocultar la vista
    viewLoading.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    
    if(timerLoadingSearch)
    {
        [timerLoadingSearch invalidate];
        timerLoadingSearch = nil;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)backSearchAction:(id)sender {

    dao *objDAO = [[dao alloc] init];

//Borramos los filtros de busqueda
    int intIdUser = [objDAO obtainCurrentIdUser];
    
    [objDAO deleteUserFilterPrice:intIdUser];
    [objDAO deleteUserFilterMarc:intIdUser];
    [objDAO deleteUserTipoOrdenamiento:intIdUser];
    
    blnExistFilter = NO;
    
    if ([objDAO obtainProductBack] == 0) {
        
        //Back desde el home
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else if ([objDAO obtainProductBack] == 2){ //Back desde las categorías
        
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
        
    }
    else{

        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        [prefs setObject:@"LoadHomeFirst" forKey:@"keyToLookupString"];
        
        //Back desde la busqueda
        UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
        UITabBarController *tab = [mainStoryBoard instantiateViewControllerWithIdentifier:@"TabBarView"];
        [tab setSelectedIndex:0];
        
        [self presentViewController:tab animated:YES completion:nil];
    }

}

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
    
}

- (IBAction)sendToDetailProduct:(id)sender {
//------------------------------------------------
/*
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    Product_Detail_ViewController *profileViewController = (Product_Detail_ViewController *)[storyboard instantiateViewControllerWithIdentifier:@"ProductoDetail"];

    [profileViewController.navigationController setNavigationBarHidden:NO];
    profileViewController.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:profileViewController animated:YES];
*/
//------------------------------------------------
}

- (IBAction)retrieveDataSearchCollectionView:(id)sender {
    
    tableViewSearch.hidden = YES;
    CollectionViewSearch.hidden = NO;
    self.CollectionViewSearch.userInteractionEnabled = YES;
    self.view.userInteractionEnabled = YES;

    imgGridOrder.image = [UIImage imageNamed:@"icono_ordenar_grilla.png"];
    
    [self retrieveGenericSearch:@"Grilla"];
    
    //-----------------------------------------
    //Nueva funcionalidad.
// viewLoading.hidden = NO;
    
// timerLoadingSearch = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loadingProductsGrid:) userInfo:nil repeats:YES];
    
    //-----------------------------------------
}

- (IBAction)retrieveDataSearchTableView:(id)sender {
    
    tableViewSearch.hidden = NO;
    CollectionViewSearch.hidden = YES;
    tableViewSearch.userInteractionEnabled = YES;
    self.view.userInteractionEnabled = YES;

    imgGridOrder.image = [UIImage imageNamed:@"icono_ordenar_lista.png"];
    
    [self retrieveGenericSearch:@"Lista"];
    
    //-----------------------------------------
    //Nueva funcionalidad.
//  viewLoading.hidden = NO;
    
//  timerLoadingSearch = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(loadingProducts:) userInfo:nil repeats:YES];
    
    //-----------------------------------------
    
}

@end
